//
//  Closures.swift
//  SwiftDemo
//
//  Created by lizq on 16/7/4.
//  Copyright © 2016年 lizq. All rights reserved.
//

import UIKit

class Closures: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        sort()
        sort2()
        sort3()
        sort4()
        sort5()
        let incrementorTen = makeIncrementor(forIncrement: 10)
        print(incrementorTen())
        print(incrementorTen())
        print(incrementorTen())
        let incrementorSeven = makeIncrementor(forIncrement: 7)
        print(incrementorSeven())
        print(incrementorTen())
        let alsoIncrementTen = incrementorTen
        print(alsoIncrementTen())
        
        let names:[String] = ["Chris","Alex","Ewa","Barry","Baniella"]
        let reversed = names.sorted(){s1,s2 in return s1 > s2 }
        print(reversed)
        let sorts = names.sorted(){(s1,s2) in s1 < s2}
        print(sorts)
        
    }
    
    func sort() {
        let names:[String] = ["Chris","Alex","Ewa","Barry","Baniella"]
        let reversed = names.sorted(by: backward)
        print(reversed)
    }
    
    /* closures 闭包
       { (paraments) -> returnType in
            statements
       }
     */
    
    func sort2() {
        let names:[String] = ["Chris","Alex","Ewa","Barry","Baniella"]
        let reversed = names.sorted(by: {(s1:String,s2:String) -> Bool in
                return s1 > s2
        })
        print(reversed)
    }
    
    func sort3() {
        let names:[String] = ["Chris","Alex","Ewa","Barry","Baniella"]
        let reversed = names.sorted(by: {s1,s2 in s1 > s2})
        print("sort 3 :\(reversed)")
    }
    
    // $0 表示第一个参数 $1表示第二个参数
    func sort4() {
        let names:[String] = ["Chris","Alex","Ewa","Barry","Baniella"]
        let reversed = names.sorted(by: {$0 > $1})
        print("sort 4 :\(reversed)")
    }

    func sort5() {
        let names:[String] = ["Chris","Alex","Ewa","Barry","Baniella"]
        let reversed = names.sorted(by: >)
        print("sort 5 :\(reversed)")
    }

    
    func backward(_ s1:String,s2:String) -> Bool{
        return s1 > s2
    }
    
    func makeIncrementor(forIncrement amount:Int) -> () -> Int {
        var runningTotal = 0;
        func incrementor() -> Int {
            runningTotal += amount
            return runningTotal
        }
        return incrementor;
    }
}
